using System;
using System.Collections.Generic;
using System.IO;
using System.Text;

namespace IppServer.Host.Ipp
{
    internal class JobInfo
    {
        public int JobId { get; set; }
        public int JobState { get; set; }
        public string JobUri { get; set; }
        public string JobName { get; set; }
    }
    
    internal static class IppResponseWriter
    {
        public static byte[] CreateSimpleOkResponse(int requestId, ushort version = 0x0101)
        {
            return CreateBaseResponse(requestId, version, 0x0000, "utf-8", "en-us", null);
        }

        public static byte[] CreateErrorResponse(int requestId, ushort statusCode, ushort version = 0x0101, string statusMessage = null)
        {
            return CreateBaseResponse(requestId, version, statusCode, "utf-8", "en-us", stream =>
            {
                // 添加自定义状态消息（如果提供）
                if (!string.IsNullOrWhiteSpace(statusMessage))
                {
                    WriteStringAttribute(stream, 0x42, "status-message", statusMessage);
                }
            });
        }

        public static byte[] CreateCreateJobResponse(int requestId, ushort version, int jobId)
        {
            return CreateBaseResponse(requestId, version, 0x0000, "utf-8", "en-us", stream =>
            {
                // job-attributes-tag (0x05) - 可选，这里不包含
                // 只返回 operation-attributes 中的 job-id
                WriteIntAttribute(stream, 0x21, "job-id", jobId);
            });
        }

        public static byte[] CreatePrintJobResponse(int requestId, ushort version, int jobId, int jobState = 9, string printerUri = null, string jobName = null, string jobStateReasons = null)
        {
            return CreateBaseResponse(requestId, version, 0x0000, "utf-8", "en-us", stream =>
            {
                // Print-Job 响应应该在 operation-attributes 中包含 job-id
                WriteIntAttribute(stream, 0x21, "job-id", jobId);
                
                // job-attributes-tag (0x02) - 作业属性
                // 注意：根据 CUPS 的实现，job-id 也在 job-attributes 中（虽然 IPP 规范说应该在 operation-attributes 中）
                // Windows 客户端可能期望在 job-attributes 中也看到 job-id
                stream.WriteByte(0x02);
                
                // job-id: 也在 job-attributes 中（CUPS 的实现方式，Windows 客户端可能期望这样）
                WriteIntAttribute(stream, 0x21, "job-id", jobId);
                
                // job-uri: Windows 客户端可能需要
                if (!string.IsNullOrEmpty(printerUri))
                {
                    var jobUri = printerUri.TrimEnd('/') + $"/{jobId}";
                    WriteStringAttribute(stream, 0x45, "job-uri", jobUri);
                }
                // job-name: Windows 客户端可能需要，用于显示作业名称
                if (!string.IsNullOrEmpty(jobName))
                {
                    WriteStringAttribute(stream, 0x41, "job-name", jobName);
                }
                // job-state: 根据 IPP 规范
                // 3=pending, 4=pending-held, 5=processing, 6=processing-stopped, 7=canceled, 8=aborted, 9=completed
                WriteIntAttribute(stream, 0x23, "job-state", jobState);
                // job-state-reasons: Windows 客户端需要，根据 IPP 规范
                if (!string.IsNullOrEmpty(jobStateReasons))
                {
                    WriteStringAttribute(stream, 0x44, "job-state-reasons", jobStateReasons);
                }
                else if (jobState == 3)
                {
                    WriteStringAttribute(stream, 0x44, "job-state-reasons", "job-queued"); // pending 状态
                }
                else if (jobState == 5)
                {
                    WriteStringAttribute(stream, 0x44, "job-state-reasons", "job-printing"); // processing 状态
                }
                else if (jobState == 9)
                {
                    WriteStringAttribute(stream, 0x44, "job-state-reasons", "job-completed-successfully");
                }
                // job-state-message: 可选，提供更详细的状态信息
                if (jobState == 3)
                {
                    WriteStringAttribute(stream, 0x42, "job-state-message", "Print job is queued");
                }
                else if (jobState == 5)
                {
                    WriteStringAttribute(stream, 0x42, "job-state-message", "Print job is being processed");
                }
                else if (jobState == 9)
                {
                    WriteStringAttribute(stream, 0x42, "job-state-message", "Print job completed successfully");
                }
            });
        }

        public static byte[] CreateGetJobsResponse(int requestId, ushort version, System.Collections.Generic.List<JobInfo> jobs = null)
        {
            return CreateBaseResponse(requestId, version, 0x0000, "utf-8", "en-us", stream =>
            {
                // Get-Jobs 响应：返回作业列表
                if (jobs != null && jobs.Count > 0)
                {
                    foreach (var job in jobs)
                    {
                        // job-attributes-tag (0x02) - 每个作业的属性
                        stream.WriteByte(0x02);
                        
                        // job-id
                        WriteIntAttribute(stream, 0x21, "job-id", job.JobId);
                        
                        // job-uri
                        if (!string.IsNullOrEmpty(job.JobUri))
                        {
                            WriteStringAttribute(stream, 0x45, "job-uri", job.JobUri);
                        }
                        
                        // job-state
                        WriteIntAttribute(stream, 0x23, "job-state", job.JobState);
                        
                        // job-name: Windows 客户端可能需要
                        if (!string.IsNullOrEmpty(job.JobName))
                        {
                            WriteStringAttribute(stream, 0x41, "job-name", job.JobName);
                        }
                        
                        // job-state-reasons: Windows 客户端需要，根据 IPP 规范
                        // 3=pending, 4=pending-held, 5=processing, 6=processing-stopped, 7=canceled, 8=aborted, 9=completed
                        if (job.JobState == 3)
                        {
                            WriteStringAttribute(stream, 0x44, "job-state-reasons", "job-queued"); // pending 状态
                        }
                        else if (job.JobState == 5)
                        {
                            WriteStringAttribute(stream, 0x44, "job-state-reasons", "job-printing"); // processing 状态
                        }
                        else if (job.JobState == 9)
                        {
                            WriteStringAttribute(stream, 0x44, "job-state-reasons", "job-completed-successfully");
                        }
                        else if (job.JobState == 6)
                        {
                            WriteStringAttribute(stream, 0x44, "job-state-reasons", "job-stopped");
                        }
                        else if (job.JobState == 7)
                        {
                            WriteStringAttribute(stream, 0x44, "job-state-reasons", "job-canceled");
                        }
                        
                        // job-state-message: Windows 客户端需要
                        if (job.JobState == 3)
                        {
                            WriteStringAttribute(stream, 0x42, "job-state-message", "Print job is queued");
                        }
                        else if (job.JobState == 5)
                        {
                            WriteStringAttribute(stream, 0x42, "job-state-message", "Print job is being processed");
                        }
                        else if (job.JobState == 9)
                        {
                            WriteStringAttribute(stream, 0x42, "job-state-message", "Print job completed successfully");
                        }
                        else if (job.JobState == 6)
                        {
                            WriteStringAttribute(stream, 0x42, "job-state-message", "Print job stopped");
                        }
                        else if (job.JobState == 7)
                        {
                            WriteStringAttribute(stream, 0x42, "job-state-message", "Print job canceled");
                        }
                    }
                }
                // 如果没有作业，不包含 job-attributes-tag，表示空列表
            });
        }

        public static byte[] CreateGetJobAttributesResponse(int requestId, ushort version, int jobId, int jobState = 9, string jobUri = null, string jobName = null)
        {
            return CreateBaseResponse(requestId, version, 0x0000, "utf-8", "en-us", stream =>
            {
                // Get-Job-Attributes 响应应该在 operation-attributes 中包含 job-id
                WriteIntAttribute(stream, 0x21, "job-id", jobId);
                
                // job-attributes-tag (0x02) - 作业属性
                stream.WriteByte(0x02);
                
                // job-uri: Windows 客户端可能需要
                if (!string.IsNullOrEmpty(jobUri))
                {
                    WriteStringAttribute(stream, 0x45, "job-uri", jobUri);
                }
                
                // job-name: Windows 客户端可能需要
                if (!string.IsNullOrEmpty(jobName))
                {
                    WriteStringAttribute(stream, 0x41, "job-name", jobName);
                }
                
                // job-state: 根据 IPP 规范
                // 3=pending, 4=pending-held, 5=processing, 6=processing-stopped, 7=canceled, 8=aborted, 9=completed
                WriteIntAttribute(stream, 0x23, "job-state", jobState);
                
                // job-state-reasons: Windows 客户端需要，根据 IPP 规范
                if (jobState == 3)
                {
                    WriteStringAttribute(stream, 0x44, "job-state-reasons", "job-queued"); // pending 状态
                }
                else if (jobState == 5)
                {
                    WriteStringAttribute(stream, 0x44, "job-state-reasons", "job-printing"); // processing 状态
                }
                else if (jobState == 9)
                {
                    WriteStringAttribute(stream, 0x44, "job-state-reasons", "job-completed-successfully");
                }
                else if (jobState == 6)
                {
                    WriteStringAttribute(stream, 0x44, "job-state-reasons", "job-stopped");
                }
                else if (jobState == 7)
                {
                    WriteStringAttribute(stream, 0x44, "job-state-reasons", "job-canceled");
                }
                
                // job-state-message: Windows 客户端需要
                if (jobState == 3)
                {
                    WriteStringAttribute(stream, 0x42, "job-state-message", "Print job is queued");
                }
                else if (jobState == 5)
                {
                    WriteStringAttribute(stream, 0x42, "job-state-message", "Print job is being processed");
                }
                else if (jobState == 9)
                {
                    WriteStringAttribute(stream, 0x42, "job-state-message", "Print job completed successfully");
                }
                else if (jobState == 6)
                {
                    WriteStringAttribute(stream, 0x42, "job-state-message", "Print job stopped");
                }
                else if (jobState == 7)
                {
                    WriteStringAttribute(stream, 0x42, "job-state-message", "Print job canceled");
                }
            });
        }

        private static readonly string[] AlwaysIncludedAttributes =
        {
            "printer-uri-supported",
            "printer-name",
            "printer-location",
            "printer-info",
            "printer-make-and-model",
            "printer-uuid",
            "printer-device-id",
            "printer-state",
            "printer-state-reasons",
            "printer-is-accepting-jobs",
            "queued-job-count",
            "operations-supported",
            "charset-supported",
            "natural-language-supported",
            "uri-authentication-supported",
            "uri-security-supported",
            "ipp-versions-supported",
            "document-format-default",
            "document-format-supported",
            "document-format-preferred",
            "media-supported",
            "media-type-supported",
            "printer-resolution-supported",
            "print-color-mode-supported",
            "print-quality-supported",
            "sides-supported",
            "copies-supported",
            "copies-default",
            "media-col-supported",
            "document-format-details-supported",
            "job-pages-per-set-supported",
            "job-impressions-supported",
            "job-password-encryption-supported",
            "printer-firmware-name",
            "printer-firmware-string-version"
        };

        public static byte[] CreatePrinterAttributesResponse(
            int requestId,
            ushort version,
            string printerUri,
            string printerName,
            string machineName,
            System.Collections.Generic.List<string> requestedAttributes = null,
            string charset = "utf-8",
            string language = "en-us",
            int? queuedJobCount = null,
            int? printerStateOverride = null)
        {
            var includedAttributes = new List<string>(); // 用于调试：记录实际包含的属性
            
            return CreateBaseResponse(requestId, version, 0x0000, charset, language, stream =>
            {
                // printer-attributes-tag (0x04)
                stream.WriteByte(0x04);

                // 如果指定了 requested-attributes，只返回请求的属性；否则返回所有标准属性
                Func<string, bool> shouldInclude;
                if (requestedAttributes == null || requestedAttributes.Count == 0)
                {
                    shouldInclude = name => { includedAttributes.Add(name); return true; };
                }
                else
                {
                    var requestedLower = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
                    foreach (var attr in requestedAttributes)
                    {
                        requestedLower.Add(attr);
                    }
                    var hasAll = requestedLower.Contains("all");
                    var alwaysInclude = new HashSet<string>(AlwaysIncludedAttributes, StringComparer.OrdinalIgnoreCase);
                    shouldInclude = name => 
                    {
                        var include = hasAll || requestedLower.Contains(name) || alwaysInclude.Contains(name);
                        if (include) includedAttributes.Add(name);
                        return include;
                    };
                }

                if (shouldInclude("printer-uri-supported"))
                {
                    // printer-uri-supported 必须是多值属性
                    // Windows 可能期望同时包含 http:// 和 ipp:// 格式的 URI
                    WriteStringAttribute(stream, 0x45, "printer-uri-supported", printerUri);
                    
                    // 如果请求的 URI 是 ipp://，也添加 http:// 版本（反之亦然）
                    if (printerUri.StartsWith("ipp://", StringComparison.OrdinalIgnoreCase))
                    {
                        var httpUri = "http://" + printerUri.Substring(6);
                        WriteStringAttribute(stream, 0x45, null, httpUri);
                    }
                    else if (printerUri.StartsWith("http://", StringComparison.OrdinalIgnoreCase))
                    {
                        var ippUri = "ipp://" + printerUri.Substring(7);
                        WriteStringAttribute(stream, 0x45, null, ippUri);
                    }
                }

                if (shouldInclude("printer-name"))
                {
                    WriteStringAttribute(stream, 0x42, "printer-name", printerName);
                }

                // operations-supported 是关键属性，必须始终返回（即使未明确请求）
                // Windows 需要知道打印机支持哪些操作才能发送打印请求
                if (shouldInclude("operations-supported") || requestedAttributes == null || requestedAttributes.Count == 0)
                {
                    WriteIntAttribute(stream, 0x23, "operations-supported", 0x0002); // Print-Job
                    WriteIntAttribute(stream, 0x23, null, 0x0004); // Validate-Job
                    WriteIntAttribute(stream, 0x23, null, 0x0005); // Create-Job
                    WriteIntAttribute(stream, 0x23, null, 0x0006); // Send-Document
                    WriteIntAttribute(stream, 0x23, null, 0x000B); // Get-Printer-Attributes
                }

                int currentPrinterState = printerStateOverride ?? 3;

                if (shouldInclude("printer-state"))
                {
                    // 如果调用方传入了打印机状态，则使用之；否则默认为 idle(3)
                    WriteIntAttribute(stream, 0x23, "printer-state", currentPrinterState);
                }

                if (shouldInclude("printer-state-reasons"))
                {
                    var printerReason = currentPrinterState == 5 ? "job-printing" :
                        currentPrinterState == 3 ? "none" :
                        currentPrinterState == 6 ? "paused" : "none";
                    WriteStringAttribute(stream, 0x44, "printer-state-reasons", printerReason);
                }

                // printer-is-accepting-jobs 是关键属性，必须始终返回（即使未明确请求）
                // Windows 需要知道打印机是否接受作业才能发送打印请求
                // 注意：即使客户端只请求了 printer-state，也应该返回 printer-is-accepting-jobs
                if (shouldInclude("printer-is-accepting-jobs") || requestedAttributes == null || requestedAttributes.Count == 0)
                {
                    WriteBooleanAttribute(stream, "printer-is-accepting-jobs", true);
                }
                else
                {
                    // 如果请求了 printer-state 或 printer-state-reasons，也应该返回 printer-is-accepting-jobs
                    var requestedLower = new HashSet<string>(requestedAttributes, StringComparer.OrdinalIgnoreCase);
                    if (requestedLower.Contains("printer-state") || requestedLower.Contains("printer-state-reasons"))
                    {
                        WriteBooleanAttribute(stream, "printer-is-accepting-jobs", true);
                    }
                }

                if (shouldInclude("queued-job-count"))
                {
                    // 如果调用方传入了队列中的作业数，则使用之；否则默认为 0
                    var count = queuedJobCount ?? 0;
                    WriteIntAttribute(stream, 0x21, "queued-job-count", count);
                }

                if (shouldInclude("printer-info"))
                {
                    WriteStringAttribute(stream, 0x42, "printer-info", $"IPP Server queue {printerName}");
                }

                if (shouldInclude("printer-location"))
                {
                    WriteStringAttribute(stream, 0x42, "printer-location", machineName ?? "IPP Server");
                }

                if (shouldInclude("printer-make-and-model"))
                {
                    WriteStringAttribute(stream, 0x42, "printer-make-and-model", printerName);
                }

                if (shouldInclude("uri-authentication-supported"))
                {
                    WriteStringAttribute(stream, 0x44, "uri-authentication-supported", "none");
                }

                if (shouldInclude("uri-security-supported"))
                {
                    WriteStringAttribute(stream, 0x44, "uri-security-supported", "none");
                }

                if (shouldInclude("ipp-versions-supported"))
                {
                    WriteStringAttribute(stream, 0x44, "ipp-versions-supported", "1.0");
                    WriteStringAttribute(stream, 0x44, null, "1.1");
                    WriteStringAttribute(stream, 0x44, null, "2.0");
                }

                if (shouldInclude("charset-supported"))
                {
                    WriteStringAttribute(stream, 0x47, "charset-supported", "utf-8");
                }

                if (shouldInclude("natural-language-supported"))
                {
                    WriteStringAttribute(stream, 0x48, "natural-language-supported", "en-us");
                    WriteStringAttribute(stream, 0x48, null, "zh-cn");
                }

                if (shouldInclude("document-format-default"))
                {
                    WriteStringAttribute(stream, 0x49, "document-format-default", "application/octet-stream");
                }

                if (shouldInclude("document-format-supported"))
                {
                    WriteStringAttribute(stream, 0x49, "document-format-supported", "application/octet-stream");
                    WriteStringAttribute(stream, 0x49, null, "application/pdf");
                    WriteStringAttribute(stream, 0x49, null, "application/postscript");
                    WriteStringAttribute(stream, 0x49, null, "image/pwg-raster");
                    WriteStringAttribute(stream, 0x49, null, "image/urf"); // Windows URF format
                    WriteStringAttribute(stream, 0x49, null, "application/vnd.hp-pcl");
                }

                if (shouldInclude("media-supported"))
                {
                    WriteStringAttribute(stream, 0x44, "media-supported", "iso_a4_210x297mm");
                }

                // Windows 可能需要的其他属性
                if (shouldInclude("printer-resolution-supported") || requestedAttributes == null)
                {
                    // 默认分辨率：300x300 dpi
                    WriteIntAttribute(stream, 0x33, "printer-resolution-supported", 300); // x
                    WriteIntAttribute(stream, 0x33, null, 300); // y
                    WriteIntAttribute(stream, 0x23, null, 3); // dpi (enum)
                }

                if (shouldInclude("print-color-mode-supported") || requestedAttributes == null)
                {
                    WriteStringAttribute(stream, 0x44, "print-color-mode-supported", "monochrome");
                    WriteStringAttribute(stream, 0x44, null, "color");
                }

                if (shouldInclude("sides-supported") || requestedAttributes == null)
                {
                    WriteStringAttribute(stream, 0x44, "sides-supported", "one-sided");
                }

                // Windows 可能需要的其他属性
                if (shouldInclude("printer-uuid"))
                {
                    // 生成一个基于打印机名称的 UUID
                    var uuid = $"urn:uuid:{Guid.NewGuid():D}";
                    WriteStringAttribute(stream, 0x45, "printer-uuid", uuid);
                }

                if (shouldInclude("printer-device-id"))
                {
                    // Windows 可能需要的设备 ID
                    WriteStringAttribute(stream, 0x42, "printer-device-id", $"MFG:Generic;MDL:{printerName};CMD:RAW;");
                }

                if (shouldInclude("mopria-certified") || shouldInclude("mopria_certified"))
                {
                    WriteStringAttribute(stream, 0x44, "mopria-certified", "1.3");
                }

                if (shouldInclude("printer-firmware-name"))
                {
                    WriteStringAttribute(stream, 0x42, "printer-firmware-name", "IPP Server");
                }

                if (shouldInclude("printer-firmware-string-version"))
                {
                    WriteStringAttribute(stream, 0x42, "printer-firmware-string-version", "1.0");
                }

                if (shouldInclude("document-format-preferred"))
                {
                    // Windows 通常期望 application/pdf 或 image/urf
                    // 使用 application/pdf 作为首选格式，因为 Windows 支持它
                    WriteStringAttribute(stream, 0x49, "document-format-preferred", "application/pdf");
                }

                if (shouldInclude("media-type-supported"))
                {
                    WriteStringAttribute(stream, 0x44, "media-type-supported", "stationery");
                }

                // 副本相关
                if (shouldInclude("copies-default"))
                {
                    WriteIntAttribute(stream, 0x21, "copies-default", 1);
                }

                if (shouldInclude("copies-supported"))
                {
                    WriteIntAttribute(stream, 0x21, "copies-supported", 1);
                    WriteIntAttribute(stream, 0x21, null, 999);
                }

                // 介质来源
                if (shouldInclude("media-source-default"))
                {
                    WriteStringAttribute(stream, 0x44, "media-source-default", "auto");
                }

                if (shouldInclude("media-source-supported"))
                {
                    WriteStringAttribute(stream, 0x44, "media-source-supported", "auto");
                }

                // 输出托盘
                if (shouldInclude("output-bin-default"))
                {
                    WriteStringAttribute(stream, 0x44, "output-bin-default", "face-down");
                }

                if (shouldInclude("output-bin-supported") || shouldInclude("printer-output-tray"))
                {
                    WriteStringAttribute(stream, 0x44, "output-bin-supported", "face-down");
                }

                // 方向
                if (shouldInclude("orientation-requested-default"))
                {
                    WriteIntAttribute(stream, 0x23, "orientation-requested-default", 3); // portrait
                }

                // 打印质量
                if (shouldInclude("print-quality-default"))
                {
                    WriteIntAttribute(stream, 0x23, "print-quality-default", 3); // normal
                }

                if (shouldInclude("print-quality-supported"))
                {
                    WriteIntAttribute(stream, 0x23, "print-quality-supported", 3); // normal
                    WriteIntAttribute(stream, 0x23, null, 4); // high
                    WriteIntAttribute(stream, 0x23, null, 5); // draft
                }

                // 颜色模式默认值
                if (shouldInclude("print-color-mode-default"))
                {
                    WriteStringAttribute(stream, 0x44, "print-color-mode-default", "monochrome");
                }

                // 多文档处理
                if (shouldInclude("multiple-document-handling-default"))
                {
                    WriteStringAttribute(stream, 0x44, "multiple-document-handling-default", "single-document");
                }

                if (shouldInclude("multiple-document-handling-supported"))
                {
                    WriteStringAttribute(stream, 0x44, "multiple-document-handling-supported", "single-document");
                }

                // 双面打印默认值
                if (shouldInclude("sides-default"))
                {
                    WriteStringAttribute(stream, 0x44, "sides-default", "one-sided");
                }

                // 每页份数
                if (shouldInclude("number-up-default"))
                {
                    WriteIntAttribute(stream, 0x21, "number-up-default", 1);
                }

                if (shouldInclude("number-up-supported"))
                {
                    WriteIntAttribute(stream, 0x21, "number-up-supported", 1);
                }

                // 演示方向
                if (shouldInclude("presentation-direction-number-up-default"))
                {
                    WriteIntAttribute(stream, 0x23, "presentation-direction-number-up-default", 0); // none
                }

                if (shouldInclude("presentation-direction-number-up-supported"))
                {
                    WriteIntAttribute(stream, 0x23, "presentation-direction-number-up-supported", 0); // none
                }

                // 装订
                if (shouldInclude("finishings-default"))
                {
                    WriteIntAttribute(stream, 0x23, "finishings-default", 3); // none
                }

                if (shouldInclude("finishings-supported"))
                {
                    WriteIntAttribute(stream, 0x23, "finishings-supported", 3); // none
                }

                // 分辨率默认值
                if (shouldInclude("printer-resolution-default"))
                {
                    WriteIntAttribute(stream, 0x33, "printer-resolution-default", 300); // x
                    WriteIntAttribute(stream, 0x33, null, 300); // y
                    WriteIntAttribute(stream, 0x23, null, 3); // dpi (enum)
                }

                // PDF 相关
                if (shouldInclude("pdf-fit-to-page-default"))
                {
                    WriteBooleanAttribute(stream, "pdf-fit-to-page-default", false);
                }

                if (shouldInclude("pdf-fit-to-page-supported"))
                {
                    WriteBooleanAttribute(stream, "pdf-fit-to-page-supported", false);
                    WriteBooleanAttribute(stream, null, true);
                }

                // PWG Raster 相关（简化实现）
                if (shouldInclude("pwg-raster-document-sheet-back"))
                {
                    WriteStringAttribute(stream, 0x44, "pwg-raster-document-sheet-back", "normal");
                }

                if (shouldInclude("pclm-raster-back-side"))
                {
                    WriteStringAttribute(stream, 0x44, "pclm-raster-back-side", "normal");
                }

                if (shouldInclude("pwg-raster-document-resolution-supported"))
                {
                    WriteIntAttribute(stream, 0x33, "pwg-raster-document-resolution-supported", 300);
                    WriteIntAttribute(stream, 0x33, null, 300);
                    WriteIntAttribute(stream, 0x23, null, 3);
                }

                if (shouldInclude("pwg-raster-document-type-supported"))
                {
                    WriteStringAttribute(stream, 0x44, "pwg-raster-document-type-supported", "black_1");
                    WriteStringAttribute(stream, 0x44, null, "sgray_8");
                    WriteStringAttribute(stream, 0x44, null, "srgb_8");
                }

                if (shouldInclude("pclm-source-resolution-supported"))
                {
                    WriteIntAttribute(stream, 0x33, "pclm-source-resolution-supported", 300);
                    WriteIntAttribute(stream, 0x33, null, 300);
                    WriteIntAttribute(stream, 0x23, null, 3);
                }

                // 打印缩放
                if (shouldInclude("print-scaling-default"))
                {
                    WriteStringAttribute(stream, 0x44, "print-scaling-default", "auto");
                }

                if (shouldInclude("print-scaling-supported"))
                {
                    WriteStringAttribute(stream, 0x44, "print-scaling-supported", "auto");
                    WriteStringAttribute(stream, 0x44, null, "none");
                    WriteStringAttribute(stream, 0x44, null, "fit");
                }

                // 介质默认值
                if (shouldInclude("media-default"))
                {
                    WriteStringAttribute(stream, 0x44, "media-default", "iso_a4_210x297mm");
                }

                // 介质集合（简化实现，返回基本值）
                if (shouldInclude("media-col-default"))
                {
                    // media-col 是集合类型，这里简化处理，返回基本结构
                    // 实际应该使用 collection 类型，但为了兼容性，先返回空或基本值
                    // Windows 可能接受空值或跳过
                }

                if (shouldInclude("media-col-ready"))
                {
                    // 同上
                }

                if (shouldInclude("media-col-database"))
                {
                    // 同上
                }

                // 页边距（以微米为单位，A4 默认边距）
                if (shouldInclude("media-left-margin-supported"))
                {
                    WriteIntAttribute(stream, 0x21, "media-left-margin-supported", 0);
                }

                if (shouldInclude("media-right-margin-supported"))
                {
                    WriteIntAttribute(stream, 0x21, "media-right-margin-supported", 0);
                }

                if (shouldInclude("media-top-margin-supported"))
                {
                    WriteIntAttribute(stream, 0x21, "media-top-margin-supported", 0);
                }

                if (shouldInclude("media-bottom-margin-supported"))
                {
                    WriteIntAttribute(stream, 0x21, "media-bottom-margin-supported", 0);
                }

                // 打印速度
                if (shouldInclude("pages-per-minute"))
                {
                    WriteIntAttribute(stream, 0x21, "pages-per-minute", 10);
                }

                if (shouldInclude("pages-per-minute-color"))
                {
                    WriteIntAttribute(stream, 0x21, "pages-per-minute-color", 5);
                }

                // 作业密码（不支持）
                if (shouldInclude("job-password-supported"))
                {
                    WriteIntAttribute(stream, 0x23, "job-password-supported", 0); // 0 = 不支持
                }

                if (shouldInclude("job-password-encryption-supported"))
                {
                    WriteStringAttribute(stream, 0x44, "job-password-encryption-supported", "none");
                }

                // 强制作业属性（空列表表示无强制要求）
                if (shouldInclude("printer-mandatory-job-attributes"))
                {
                    // 多值属性，空列表表示无强制要求
                    // Windows 可能接受空值
                }

                // 介质集合支持（简化实现）
                if (shouldInclude("media-col-supported"))
                {
                    // media-col 是集合类型，这里返回支持的集合成员
                    // 简化实现：返回基本成员
                    WriteStringAttribute(stream, 0x44, "media-col-supported", "media-size");
                    WriteStringAttribute(stream, 0x44, null, "media-type");
                }

                // 文档格式详情支持
                if (shouldInclude("document-format-details-supported"))
                {
                    // 返回支持的文档格式详情属性
                    WriteStringAttribute(stream, 0x44, "document-format-details-supported", "document-format");
                    WriteStringAttribute(stream, 0x44, null, "document-format-version");
                }

                // 作业每套页数支持
                if (shouldInclude("job-pages-per-set-supported"))
                {
                    WriteBooleanAttribute(stream, "job-pages-per-set-supported", true);
                }

                // 作业印象数支持
                if (shouldInclude("job-impressions-supported"))
                {
                    WriteBooleanAttribute(stream, "job-impressions-supported", true);
                }
            });
        }

        private static byte[] CreateBaseResponse(int requestId, ushort version, ushort statusCode, string charset, string language, System.Action<Stream> writeBody)
        {
            using (var stream = new MemoryStream())
            {
                // 使用请求的版本（默认 1.1）
                stream.WriteByte((byte)((version >> 8) & 0xFF));
                stream.WriteByte((byte)(version & 0xFF));

                stream.WriteByte((byte)(statusCode >> 8));
                stream.WriteByte((byte)(statusCode & 0xFF));

                stream.WriteByte((byte)((requestId >> 24) & 0xFF));
                stream.WriteByte((byte)((requestId >> 16) & 0xFF));
                stream.WriteByte((byte)((requestId >> 8) & 0xFF));
                stream.WriteByte((byte)(requestId & 0xFF));

                // operation-attributes-tag (0x01)
                stream.WriteByte(0x01);
                WriteStringAttribute(stream, 0x47, "attributes-charset", charset ?? "utf-8");
                WriteStringAttribute(stream, 0x48, "attributes-natural-language", language ?? "en-us");
                
                // status-message (optional but Windows may expect it)
                if (statusCode == 0x0000)
                {
                    WriteStringAttribute(stream, 0x42, "status-message", "successful-ok");
                }

                writeBody?.Invoke(stream);

                stream.WriteByte(0x03); // end-of-attributes
                return stream.ToArray();
            }
        }

        private static void WriteStringAttribute(Stream stream, byte tag, string name, string value)
        {
            // 根据 IPP 规范：
            // - 属性名必须是 US-ASCII
            // - 字符串值按照 attributes-charset 编码（我们统一使用 UTF-8）
            var nameBytes = string.IsNullOrEmpty(name) ? null : Encoding.ASCII.GetBytes(name);
            var valueBytes = Encoding.UTF8.GetBytes(value ?? string.Empty);

            stream.WriteByte(tag);
            var nameLength = nameBytes?.Length ?? 0;
            stream.WriteByte((byte)(nameLength >> 8));
            stream.WriteByte((byte)(nameLength & 0xFF));
            if (nameLength > 0)
            {
                stream.Write(nameBytes, 0, nameLength);
            }

            stream.WriteByte((byte)(valueBytes.Length >> 8));
            stream.WriteByte((byte)(valueBytes.Length & 0xFF));
            stream.Write(valueBytes, 0, valueBytes.Length);
        }

        private static void WriteIntAttribute(Stream stream, byte tag, string name, int value)
        {
            var nameBytes = string.IsNullOrEmpty(name) ? null : Encoding.ASCII.GetBytes(name);

            stream.WriteByte(tag);
            var nameLength = nameBytes?.Length ?? 0;
            stream.WriteByte((byte)(nameLength >> 8));
            stream.WriteByte((byte)(nameLength & 0xFF));
            if (nameLength > 0)
            {
                stream.Write(nameBytes, 0, nameLength);
            }

            // 4-byte integer
            stream.WriteByte(0x00);
            stream.WriteByte(0x04);
            stream.WriteByte((byte)((value >> 24) & 0xFF));
            stream.WriteByte((byte)((value >> 16) & 0xFF));
            stream.WriteByte((byte)((value >> 8) & 0xFF));
            stream.WriteByte((byte)(value & 0xFF));
        }

        private static void WriteBooleanAttribute(Stream stream, string name, bool value)
        {
            var nameBytes = string.IsNullOrEmpty(name) ? null : Encoding.ASCII.GetBytes(name);
            stream.WriteByte(0x22);
            var nameLength = nameBytes?.Length ?? 0;
            stream.WriteByte((byte)(nameLength >> 8));
            stream.WriteByte((byte)(nameLength & 0xFF));
            if (nameLength > 0)
            {
                stream.Write(nameBytes, 0, nameLength);
            }

            stream.WriteByte(0x00);
            stream.WriteByte(0x01);
            stream.WriteByte(value ? (byte)0x01 : (byte)0x00);
        }
    }
}

